package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import utils.BlockUtils;
import utils.FileInfo;
import utils.FileType;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(args.length != 2) {
			System.out.println("This command needs 2 args");
			System.exit(0);
		}
		String root = args[0];
		String dest = args[1];
		root = BlockUtils.prepareRoot(root);
		dest = BlockUtils.prepareDest(dest, root);
		//В начале итерации мы находимся в корне
		File f = BlockUtils.checkDestFile(root, dest);
		if(f == null) {
			System.out.println("we haven't found file");
			System.exit(1);
		}
		File f2 = BlockUtils.checkDestToCatalogue(root, dest);
		Integer extractBlockNumber = BlockUtils.extractBlockNumber(f);
		BlockUtils.removeCataloguePointer(f2, extractBlockNumber, root);
		remove(f, root);
	}

	private static void remove(File src, String root) {
		FileInfo fileInfo = BlockUtils.getFileInfo(src);
		if(fileInfo.getType().equals(FileType.CATALOGUE_TYPE)) {
			removeCatalogue(src, root);
		} else {
			removeFile(src,root);
		}
	}


	private static void removeFile(File src, String root) {
		Integer number = 0;
		FileInputStream fin = null;
		try {
			if (src.canRead() && src.canWrite()) {
				try {
					while(src != null) {
						byte[] b = new byte[(int) src.length()];
						fin = new FileInputStream(src);
						fin.read(b);
						number = BlockUtils.getNextFile(b);
						BlockUtils.clearBlock(src, src.length());
						if(number > 0 ) 
							src = BlockUtils.getBlockByNumber(number, root);
						else
							src = null;
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						if(fin != null)
							fin.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
		        }
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	private static void removeCatalogue(File src, String root) {
		if (src.canRead() && src.canWrite()) {
			List<File> listFiles = BlockUtils.getListFiles(src, root);
			BlockUtils.clearBlock(src, src.length());
			for(File file :listFiles) {
				remove(file, root);
			}
		}	
	}
}
